package nix.mall.sso.service.impl;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import nix.mall.common.pojo.NixMallResult;
import nix.mall.jedis.JedisClient;
import nix.mall.mapper.UserMapper;
import nix.mall.pojo.User;
import nix.mall.pojo.UserExample;
import nix.mall.pojo.UserExample.Criteria;
import nix.mall.sso.service.UserService;
import nix.mall.utils.JsonUtils;

/**
 * 用户处理Service
 */
@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private JedisClient jedisClient;
	
	@Value("${USER_SESSION}")
	private String USER_SESSION;
	
	@Value("${SESSION_EXPIRE}")
	private Integer SESSION_EXPIRE;
	
	@Override
	public NixMallResult checkData(String data, int type) {
		UserExample example = new UserExample();
		Criteria criteria = example.createCriteria();
		// 设置查询条件
		if (type == 1) {// 用户名
			criteria.andUsernameEqualTo(data);
		} else if (type == 2) {// 手机号
			criteria.andPhoneEqualTo(data);
		} else if (type == 3) {// Email
			criteria.andEmailEqualTo(data);
		} else {
			return NixMallResult.build(400, "请求参数包含非法数据！");
		}
		// 执行查询
		List<User> list = userMapper.selectByExample(example);
		if (list != null && list.size() > 0) {
			// 查询到数据，返回false
			return NixMallResult.ok(false);
		} else {
			// 数据可用
			return NixMallResult.ok(true);
		}
	}

	@Override
	public NixMallResult register(User user) {		
		// 数据校验
		if (StringUtils.isBlank(user.getUsername())) {
			return NixMallResult.build(400, "用户名不能为空！");
		}
		if (StringUtils.isBlank(user.getPassword())) {
			return NixMallResult.build(400, "密码不能为空！");
		}

		if (!(boolean) checkData(user.getUsername(), 1).getData()) {
			return NixMallResult.build(400, "该用户名已被占用！");
		}
		if (StringUtils.isNotBlank(user.getPhone())) {
			if (!(boolean) checkData(user.getPhone(), 2).getData()) {
				return NixMallResult.build(400, "该手机号已被占用！");
			}
		}
		if (StringUtils.isNotBlank(user.getEmail())) {
			if (!(boolean) checkData(user.getEmail(), 3).getData()) {
				return NixMallResult.build(400, "该Email已被占用！");
			}
		}
		// 补全pojo属性
		user.setCreated(new Date());
		user.setUpdated(new Date());
		// 密码MD5加密
		user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
		userMapper.insert(user);
		// 返回
		return NixMallResult.ok();
	}

	@Override
	public NixMallResult login(String username, String password) {
		// 数据校验
		if (StringUtils.isBlank(username)) {
			return NixMallResult.build(400, "用户名不能为空！");
		}
		if (StringUtils.isBlank(password)) {
			return NixMallResult.build(400, "密码不能为空！");
		}
		// 查询数据库
		UserExample example = new UserExample();
		Criteria criteria = example.createCriteria();
		criteria.andUsernameEqualTo(username);		
		List<User> list = userMapper.selectByExample(example);
		if (list == null || list.size() == 0) {
			return NixMallResult.build(400, "用户名不存在！");
		}
		User user = list.get(0);
		// 密码MD5加密校验
		if (!DigestUtils.md5DigestAsHex(password.getBytes()).equals(user.getPassword())) {
			return NixMallResult.build(400, "密码不正确！");
		}		
		// 生成token（uuid）
		String token = UUID.randomUUID().toString();
		// 把用户信息保存到Redis（key为token，value为用户信息）
		// 清空密码
		user.setPassword(null);
		jedisClient.set(USER_SESSION + ":" + token, JsonUtils.objectToJson(user));
		// 设置key过期时间
		jedisClient.expire(USER_SESSION + ":" + token, SESSION_EXPIRE);
		// 返回（返回token）
		return NixMallResult.ok(token);
	}

	@Override
	public NixMallResult getUserByToken(String token) {
		String json = jedisClient.get(USER_SESSION + ":" + token);
		if (StringUtils.isBlank(json)) {
			return NixMallResult.build(400, "用户未登陆或已过期！");
		}
		// 重置key过期时间，保持登陆状态
		jedisClient.expire(USER_SESSION + ":" + token, SESSION_EXPIRE);
		// 转回pojo再返回，直接返回json会当字符串处理，带转移符
		User user = JsonUtils.jsonToPojo(json, User.class);
		return NixMallResult.ok(user);
	}

	@Override
	public NixMallResult logout(String token) {
		jedisClient.expire(USER_SESSION + ":" + token, 0);
		return NixMallResult.ok();
	}

}
